package 反射5;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MyDbutils {
    public static <T> List<T> findList(String sql,Class<T> c){
        ArrayList<T> arraylist = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/practice?useSSL=false&serverTimezone=UTC", "root", "123456");
//            Statement statement = conn.createStatement();
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery(sql);
            System.out.println("resultSet = " + resultSet);
//            --------------------------------------------------------------
            //从结果集合中获取结果集的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            System.out.println("metaData = " + metaData);
            //获取集合中列数
            int count = metaData.getColumnCount();
            System.out.println("count = " + count);
            //解析结果集---while (resultSet.next()) 这行代码开始遍历数据库查询返回的结果集,
            // 处理从数据库结果集中获取的数据，并将其封装成实体对象
            while(resultSet.next()){
                //动态获取一行数据后，封装成实体对象
                T t = c.newInstance();
                System.out.println("t = " + t);
                for (int i=1;i<=count;i++){//用于遍历结果集中的每一列
                    //通过列的序号获取列值
                    Object value = resultSet.getObject(i);
                    System.out.println("value = " + value);
                    if(value!=null){
                        //通过列的序号获取列名
                        String columnName = metaData.getColumnName(i);
                        System.out.println("columnName = " + columnName);
                        Field declaredField = c.getDeclaredField(columnName);
                        declaredField.setAccessible(true);//允许访问Javabean私有属性
                        declaredField.set(t,value);
                    }
                }
                arraylist.add(t);
            }
//            --------------------------------------------------------------
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return arraylist;
    }
}
